<template>
  <a-modal :open="open" width="1200px" title="入区登记" centered @cancel="onCancel">
    <template #footer>
      <a-button :disabled="!formState.inplsh" @click="onPrint">床卡</a-button>
      <a-button :disabled="!formState.inplsh" @click="onPrintWrist">腕带</a-button>
      <a-button key="back" @click="onCancel">返回</a-button>
      <a-button key="submit" type="primary" @click="onSave">保存</a-button>
      <div class="absolute top-[-9999px] hidden">
        <a-button ref="printMe" v-print="{ id: 'printMe' }">打印</a-button>
        <a-button ref="printMeBeb" v-print="{ id: 'printMeBeb' }">打印</a-button>
        <PrintView id="printMe" :print-data="printData" />
        <PrintViewBeb id="printMeBeb" :print-data="printData" />
      </div>
    </template>
    <div class="w-full flex-between">
      <div class="w-1/4 pr-1 mr-2 border-dashed border-r-2 overflow-hidden">
        <a-spin :spinning="loading" wrapper-class-name="mt-2">
          <div class="card-box">
            <div v-if="!dataSource.length" class="w-full h-full flex-center">
              <a-empty />
            </div>
            <template v-for="item in dataSource" :key="item">
              <a-card
                bordered
                :class="{ 'card-item mr-1': true, active: item.inplsh === formState.inplsh }"
                :body-style="{ padding: 0 }"
                @click="onCardClick(item)"
              >
                <div class="item-header items-center">
                  <a-avatar :src="avatarMan" />
                  <div class="flex-1 ml-2 flex-between">
                    <div class="font-semibold">
                      {{ item.brName || '姓名' }}
                    </div>
                    <div>
                      <span class="mr-2">{{ item.brXb }}</span> {{ item.brAge }}
                    </div>
                    <div>预计住院{{ item.expectDays }}天</div>
                  </div>
                </div>
                <div class="p-2">
                  <div>
                    <span>住院号</span>：<span>{{ item.admissionCode }}</span>
                  </div>
                  <div>
                    <span>科室</span>：<span>{{ item.ksmc }}</span>
                  </div>
                  <div>
                    <span>病区</span>：<span>{{ item.wardName }}</span>
                  </div>
                  <div>
                    <!-- 如果是转区，把目标床位清空 -->
                    <span>目标床位</span>：<span>{{ item?.isTransferZone === 1 ? '' : item.lastBedCode }}</span>
                  </div>
                  <div>
                    <span>入院时间</span>：<span>{{ item.admissionTime }}</span>
                  </div>
                </div>
              </a-card>
            </template>
          </div>
        </a-spin>
      </div>
      <div class="w-3/4 h-fit">
        <a-form ref="formRef" :model="formState" class="pl-2" :label-col="{ style: { width: '100px' } }">
          <BaseTitle title="住院信息" />
          <a-form-item label="科室" name="ksmc" class="w-1/3"> {{ formState.ksmc }} </a-form-item>
          <a-form-item label="病区" name="wardName" class="w-1/3">
            {{ formState.wardName }}
          </a-form-item>
          <a-form-item label="床位" class="w-1/3" name="lastBedCode" required>
            <SelectTable
              v-model:value="formState.lastBedCode"
              type="床位"
              placeholder="请输入"
              :search-params="{ bqid: formState.lastWardId }"
              :row-disabled="(row) => row.status === 2 || row.status === 1"
              @select="(bed) => (formState.lastBedCode = bed.bedCode)"
            />
          </a-form-item>
          <a-form-item label="入区时间" class="w-1/3">
            <a-date-picker v-model:value="formState.lastDeptRegTime" show-time value-format="YYYY-MM-DD HH:mm" />
          </a-form-item>
          <a-form-item label="护理等级" class="w-1/3" required>
            <SelectLevel v-model:value="formState.lastNurseLevelId" trigger="init" />
          </a-form-item>
          <a-form-item label="护理组" class="w-1/3">
            <SelectTable v-model:value="formState.nurseGroupIdName" class="w-full" type="护理医疗" @select="(item) => onSelectNursing('nurseGroupId', item)" />
          </a-form-item>
          <a-form-item label="医疗组" class="w-1/3">
            <SelectTable
              v-model:value="formState.medicalGroupIdName"
              class="w-full"
              type="护理医疗"
              @select="(item) => onSelectNursing('medicalGroupId', item)"
            />
          </a-form-item>
          <a-form-item label="责任护士" class="w-1/3" required>
            <SelectTable
              v-model:value="formState.lastDutyNurseName"
              class="w-full"
              type="住院入区护士"
              :search-params="{ wardId: formState.lastWardId }"
              @select="(item) => onSelectDoctor('lastDutyNurse', item)"
            />
          </a-form-item>
          <a-form-item label="质控护士" class="w-1/3">
            <SelectTable
              v-model:value="formState.lastQcNurseName"
              class="w-full"
              type="住院入区护士"
              :search-params="{ wardId: formState.lastWardId }"
              @select="(item) => onSelectDoctor('lastQcNurse', item)"
            />
          </a-form-item>
          <a-form-item label="护士长" class="w-1/3">
            <SelectTable
              v-model:value="formState.lastHeadNurseName"
              class="w-full"
              type="住院入区护士"
              :search-params="{ wardId: formState.lastWardId }"
              @select="(item) => onSelectDoctor('lastHeadNurse', item)"
            />
          </a-form-item>
          <a-form-item label="责任医生" class="w-1/3">
            <SelectTable v-model:value="formState.lastDutyDoctorName" class="w-full" type="医生" @select="(item) => onSelectDoctor('lastDutyDoctor', item)" />
          </a-form-item>
          <a-form-item label="住院医生" class="w-1/3" required>
            <SelectTable v-model:value="formState.lastInpDoctorName" class="w-full" type="医生" @select="(item) => onSelectDoctor('lastInpDoctor', item)" />
          </a-form-item>
          <a-form-item label="主治医生" class="w-1/3" required>
            <SelectTable
              v-model:value="formState.lastAttendingDoctorName"
              class="w-full"
              type="医生"
              @select="(item) => onSelectDoctor('lastAttendingDoctor', item)"
            />
          </a-form-item>
          <a-form-item label="主任(副)医生" class="w-1/3" required>
            <SelectTable
              v-model:value="formState.lastDirectorDoctorName"
              class="w-full"
              type="医生"
              @select="(item) => onSelectDoctor('lastDirectorDoctor', item)"
            />
          </a-form-item>
          <a-form-item label="科主任" class="w-1/3">
            <SelectTable
              v-model:value="formState.lastDeptDirectorName"
              class="w-full"
              type="医生"
              @select="(item) => onSelectDoctor('lastDeptDirector', item)"
            />
          </a-form-item>
          <template v-if="formState.ksmc === '眼科'">
            <BaseTitle title="视力信息" />
            <div class="border border-solid w-full mb-3">
              <div class="flex">
                <div class="table-cell w-1/2 py-2 text-center">右眼(OD)</div>
                <div class="table-cell w-1/2 py-2 text-center">左眼(OS)</div>
              </div>
              <div class="flex">
                <div class="w-1/2">
                  <div class="flex">
                    <div class="table-cell p-3 w-1/4">远视力(裸眼)</div>
                    <div class="table-cell p-3 w-1/4 relative">
                      <EditCell title="远视力裸眼">
                        <a-input v-model:value="formState.odDistanceVisionNe" placeholder="请输入" />
                      </EditCell>
                    </div>
                    <div class="table-cell p-3 w-1/4">近视力(裸眼)</div>
                    <div class="table-cell p-3 w-1/4 relative">
                      <EditCell title="近视力裸眼">
                        <a-input v-model:value="formState.odNearVisionNe" placeholder="请输入" />
                      </EditCell>
                    </div>
                  </div>
                  <div class="flex">
                    <div class="table-cell p-3 w-1/4">远视力(矫正)</div>
                    <div class="table-cell p-3 w-1/4 relative">
                      <EditCell title="远视力">
                        <a-input v-model:value="formState.odDistanceVisionCorr" placeholder="请输入" />
                      </EditCell>
                    </div>
                    <div class="table-cell p-3 w-1/4">近视力(矫正)</div>
                    <div class="table-cell p-3 w-1/4 relative">
                      <EditCell title="近视力">
                        <a-input v-model:value="formState.odNearVisionCorr" placeholder="请输入" />
                      </EditCell>
                    </div>
                  </div>
                </div>
                <div class="w-1/2">
                  <div class="flex">
                    <div class="table-cell p-3 w-1/4">远视力(裸眼)</div>
                    <div class="table-cell p-3 w-1/4 relative">
                      <EditCell title="远视力裸眼">
                        <a-input v-model:value="formState.osDistanceVisionNe" placeholder="请输入" />
                      </EditCell>
                    </div>
                    <div class="table-cell p-3 w-1/4">近视力(裸眼)</div>
                    <div class="table-cell p-3 w-1/4 relative">
                      <EditCell title="近视力裸眼">
                        <a-input v-model:value="formState.osNearVisionNe" placeholder="请输入" />
                      </EditCell>
                    </div>
                  </div>
                  <div class="flex">
                    <div class="table-cell p-3 w-1/4">远视力(矫正)</div>
                    <div class="table-cell p-3 w-1/4 relative">
                      <EditCell title="远视力">
                        <a-input v-model:value="formState.osDistanceVisionCorr" placeholder="请输入" />
                      </EditCell>
                    </div>
                    <div class="table-cell p-3 w-1/4">近视力(矫正)</div>
                    <div class="table-cell p-3 w-1/4 relative">
                      <EditCell title="近视力">
                        <a-input v-model:value="formState.osNearVisionCorr" placeholder="请输入" />
                      </EditCell>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </template>

          <BaseTitle title="体征信息" />
          <a-form-item label="身高" class="w-1/3"> <a-input v-model:value="formState.height" v-input:float placeholder="请输入" suffix="cm" /></a-form-item>
          <a-form-item label="体重" class="w-1/3">
            <a-input v-model:value="formState.weight" v-input:float placeholder="请输入" suffix="kg" />
          </a-form-item>
          <!-- <a-form-item label="BMI" class="w-1/3">
            <a-input v-model:value="formState.BMI" placeholder="请输入" disabled />
          </a-form-item> -->
          <a-form-item label="体温" class="w-1/3">
            <a-input v-model:value="formState.tpr1" placeholder="请输入" suffix="℃" />
          </a-form-item>
          <a-form-item label="血压" class="w-2/3">
            <div class="flex">
              <a-input v-model:value="formState.sbp" placeholder="收缩压" class="flex-1" />
              <div class="mx-2 text-center">/</div>
              <a-input v-model:value="formState.dbp" placeholder="舒张压" class="flex-1" suffix="mmHg" />
            </div>
          </a-form-item>
          <!-- <a-form-item label="危重级别" class="w-1/3">
            <SelectItem v-model:value="formState.wzjb" type="DT00251" />
          </a-form-item>
          <a-form-item label="病理状态" class="w-1/3">
            <SelectItem v-model:value="formState.blzt" type="DT00252" />
          </a-form-item> -->
          <a-form-item label="呼吸" class="w-1/3">
            <a-input v-model:value="formState.brt1" placeholder="请输入" suffix="次/分" />
          </a-form-item>
          <a-form-item label="脉搏" class="w-1/3">
            <a-input v-model:value="formState.pul1" placeholder="请输入" suffix="次/分" />
          </a-form-item>
          <a-form-item label="心率" class="w-1/3">
            <a-input v-model:value="formState.xl" placeholder="请输入" suffix="次/分" />
          </a-form-item>
          <!-- <a-form-item label="生理状态" class="w-1/3">
            <SelectItem v-model:value="formState.slzt" type="DT00253" />
          </a-form-item> -->
          <BaseTitle title="过敏史" />
          <a-form-item label="过敏史" class="w-full">
            <!-- 过敏史 -->
            <SelectAllergyModal v-model:value="formState.brGms" :source-data="formState.patientAllergys" @success="formState.patientAllergys = $event.data" />
          </a-form-item>
          <BaseTitle title="费用信息" />
          <a-form-item label="押金金额" class="w-full"> ￥{{ formState.dpJe || 0 }} </a-form-item>
        </a-form>
      </div>
    </div>
    <!-- 过敏史 -->
    <!-- <AllergicModel v-model:open="allergicOpen" :row-data="formState.gms" @success="onSuccess" /> -->
  </a-modal>
</template>
<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import BaseTitle from '@/components/BaseTitle'
import avatarMan from '@/assets/images/avatar-man.png'
import SelectTable from '@/components/SelectTable'
import useUserStore from '@/store/user'
import { post } from '@/utils/request'
import { formatAmount } from '@/utils/format'
import SelectAllergyModal from '@/components/SelectAllergy'
// import SelectLevel from '@/components/SelectLevel'
import { getSystemConfig } from '@/utils/systemConfig'
import useStore from '../../store'
import PrintView from './PrintView.vue'
import PrintViewBeb from './PrintViewBeb.vue'

const store = useStore()
const { empId } = useUserStore()
const props = defineProps({
  open: Boolean,
  rowData: {
    type: Object,
    default: () => ({})
  }
})

const dataSource = ref([])
const formRef = ref()
const loading = ref(false)
const printData = ref({})
const printMe = ref()
const printMeBeb = ref()

const formState = ref({
  cwh: null,
  lastDeptRegTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  height: '',
  weight: '',
  brGms: '',
  rksj: dayjs().format('YYYY-MM-DD HH:mm:ss')
})

const emit = defineEmits(['update:open', 'close', 'success'])
const onCardClick = (item) => {
  formState.value = { ...item }
  formState.value.lastDeptRegTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
  formState.value.bedCode = item?.lastBedCode
  // isTransferZone  0  入院入区   1  转区入区
  if (item?.isTransferZone === 0) {
    formState.value.lastBedCode = props.rowData.isBedCode ? props.rowData?.bedCode : item?.lastBedCode
  } else {
    formState.value.lastBedCode = ''
  }
}

// 护理医疗
const onSelectNursing = (key, item) => {
  formState.value[key] = item.id
  formState.value[key + 'Name'] = item.groupName
}

const onSelectDoctor = (key, item) => {
  formState.value[key] = item.empId
  formState.value[key + 'Name'] = item.empName
}
const getData = async () => {
  loading.value = true
  const { code, data } = await post('/inp/zydj/getInpRecordList', {
    bqbh: store.areaCode, //病区编号
    status: 3,
    inpLshList: props.rowData.inplsh ? [props.rowData.inplsh] : [] //拼音简码
  })
  loading.value = false
  if (code === 0) {
    dataSource.value = data
    onCardClick(data[0])
  }
  !formState.value.lastQcNurse && getDoctorByCode('INP_QC_DEFAULT_NURSE_CODE')
  !formState.value.lastHeadNurse && getDoctorByCode('INP_DEFAULT_HEAD_NURSE_CODE')
}
// 'INP_QC_DEFAULT_NURSE_CODE', //质控护士
// 'INP_DEFAULT_HEAD_NURSE_CODE', //护士长
const getDoctorByCode = async (settingCode) => {
  const { code, data } = await post('common/emp/getEmpInfoBySettingCode', {
    settingCode
  })
  if (code === 0) {
    if (settingCode === 'INP_QC_DEFAULT_NURSE_CODE') {
      formState.value.lastQcNurse = data.empId
      formState.value.lastQcNurseName = data.empName
    }
    if (settingCode === 'INP_DEFAULT_HEAD_NURSE_CODE') {
      formState.value.lastHeadNurse = data.empId
      formState.value.lastHeadNurseName = data.empName
    }
  }
}

// 床卡打印
const onPrint = async () => {
  const { code, msg, data } = await post('/inp/Print/bedCardPrint', {
    inplsh: formState.value.inplsh
  })
  if (code !== 0) return message.error(msg)
  if (getSystemConfig('NAVYHIS_MODE') === '1') {
    printData.value = JSON.parse(data)
    setTimeout(() => {
      printMeBeb.value.$el.click()
    }, 1000)
  } else {
    window.openExe?.rpt(data) //调用winform打印
  }
}

// 腕带
const onPrintWrist = async () => {
  const { code, msg, data } = await post('/inp/Print/inpWristbandsPrint', {
    inplsh: formState.value.inplsh
  })
  if (code !== 0) return message.error(msg)
  if (getSystemConfig('NAVYHIS_MODE') === '1') {
    printData.value = JSON.parse(data)
    setTimeout(() => {
      printMe.value.$el.click()
    }, 1000)
  } else {
    window.openExe?.rpt(data) //调用winform打印
  }
}

watch(
  () => props.open,
  (value) => {
    !value && formRef.value.resetFields()
    value && getData()
    // 'INP_QC_DEFAULT_NURSE_CODE', //质控护士
    // 'INP_DEFAULT_HEAD_NURSE_CODE', //护士长
  }
)
// watch(
//   () => formState.value.patientAllergys,
//   (value) => {
//     formState.value.brGms = value.map((v) => v.dictItemName + ':' + ['未查', '无', '有'][v.status]).join('；')
//   }
// )

watch(
  () => [formState.value.weight, formState.value.height],
  (value) => {
    if (value[0] && value[1]) {
      formState.value.BMI = formatAmount(formState.value.weight / ((formState.value.height / 100) * (formState.value.height / 100)))
    }
  }
)
const onCancel = () => {
  emit('update:open', false)
  emit('close')
}

const onSave = async () => {
  formState.value.inpAdvId = formState.value.inpTransferZone ? JSON.parse(JSON.stringify(formState.value.inpTransferZone.inpAdvId)) : undefined
  delete formState.value.inpTransferZone
  if (!formState.value.lastDutyNurseName) return message.error('请选择责任护士')
  if (!formState.value.lastInpDoctorName) return message.error('请选择住院医生')
  if (!formState.value.lastDirectorDoctorName) return message.error('请选择主任(副)医生')
  if (!formState.value.inplsh) return message.error('请选择患者')
  if (!formState.value.lastNurseLevelId) return message.error('请选择护理等级')
  try {
    await formRef.value.validateFields()
    const { code, msg } = await post('/inp/zyhs/doTransferInWard', {
      admissionEmpId: empId, //操作人
      ...formState.value
    })
    if (code === 0) {
      message.success(msg || '操作成功')
      emit('update:open', false)
      store.getStatusCount()
      emit('success')
      const { code: codeBing, msg: msgBing } = await post('/med/MedicalRecord/doSaveMrBazbInp', {
        inplsh: formState.value.inplsh
      })
      if (codeBing !== 0) return message.error(msgBing)
    } else {
      message.error(msg || '操作失败')
    }
  } catch (errorInfo) {
    message.error('请输入完整')
  }
}
</script>
<style lang="less" scoped>
.card-box {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  height: 650px;
  overflow: auto;
  .card-item + .card-item {
    margin-top: 16px;
  }
  .card-item {
    width: 100%;
    height: fit-content;
    cursor: pointer;
    &:hover {
      background-color: #00000005;
      border: 1px solid var(--primary-color);
    }
    &.active {
      border: 1px solid var(--primary-color);
      .item-header {
        color: #fff;
        background-color: var(--primary-color);
      }
    }
    .item-header {
      position: relative;
      display: flex;
      padding: 8px;
      background-color: #00000010;
    }
  }
}
:deep(.ant-form) {
  display: flex;
  flex-flow: row wrap;
  min-width: 0;
  .ant-form-item {
    .ant-form-item-label {
      width: 80px;
    }
  }
  .ant-picker {
    width: 100%;
  }
}

.table-cell {
  @apply border border-solid border-t-0 border-l-0;
}
</style>
